package com.fept.msgcore.msgserver.senderinfo;

import com.fept.msgcore.msgserver.netty.handler.ProtocolMessageDecoder;
import com.fept.msgcore.msgserver.protocol.model.message.SenderModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by Srma on 2/9/2017.
 */
public class SenderInfoManager {
    private static Logger logger = LoggerFactory.getLogger(SenderInfoManager.class);
    private Map<Integer, SenderModel> idMap = new ConcurrentHashMap<Integer, SenderModel>();

    private static SenderInfoManager senderInfoManager = new SenderInfoManager();

    /**
     *
     * @return
     */
    public static SenderInfoManager getInstance() {
        return senderInfoManager;
    }

    /**
     * 清空超时的sender
     *
     * @param deltaTime
     */
    public void refreshSenderModels(long deltaTime) {
        logger.info("refreshSenderModels");
        Iterator<SenderModel> iSenIterator = this.idMap.values().iterator();
        long timestamp = System.currentTimeMillis();
        while (iSenIterator.hasNext()) {
            SenderModel senderModel = iSenIterator.next();
            if (timestamp - senderModel.getLastRefreshTime() > deltaTime) {
                logger.info("sender model removed: " + senderModel);
                iSenIterator.remove();
            }
        }
    }

    /**
     *
     * @param id
     * @param ip
     * @return
     * @throws SQLException
     */
    public SenderModel getSenderModel(int id) {
        return this.idMap.get(id);
    }

    /**
     *
     * @param senderID
     * @param senderIP
     */
    public void updateSenderInfoModel(int senderID, String senderIP,int senderPort) {
        SenderModel senderModel = this.idMap.get(senderID);
        /**
         * 如果sender不存在,未注册
         */
        if (senderModel == null) {
            senderModel = new SenderModel();
        }

        senderModel.setSenderID(senderID);
        senderModel.setSenderIP(senderIP);
        senderModel.setSenderPort(senderPort);
        senderModel.setLastRefreshTime(System.currentTimeMillis());

        this.idMap.put(senderID, senderModel);
    }



    /**
     *
     * @return
     */
    public List<SenderModel> listClients() {
        List<SenderModel> listClients = new ArrayList<SenderModel>();
        for (SenderModel sender : this.idMap.values()) {
            listClients.add(sender);
        }
        return listClients;
    }
}
